// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/functions/function_registry.h>

#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <iterator>
#include <optional>
#include <sstream>
#include <pollux/common/base/exceptions.h>
#include <pollux/core/simple_function_metadata.h>
#include <pollux/expression/function_call_to_special_form.h>
#include <pollux/expression/function_signature.h>
#include <pollux/expression/signature_binder.h>
#include <pollux/expression/simple_function_registry.h>
#include <pollux/expression/vector_function.h>
#include <pollux/type/type.h>

namespace kumo::pollux {
    namespace {
        void populate_simple_function_signatures(FunctionSignatureMap &map) {
            const auto &functions = exec::simple_functions();
            for (const auto &functionName: functions.get_function_names()) {
                map[functionName] = functions.get_function_signatures(functionName);
            }
        }

        void populate_vector_function_signatures(FunctionSignatureMap &map) {
            auto functions = exec::vectorFunctionFactories();
            functions.withRLock([&map](const auto &locked) {
                for (const auto &it: locked) {
                    const auto &allSignatures = it.second.signatures;
                    auto &curSignatures = map[it.first];
                    std::transform(
                        allSignatures.begin(),
                        allSignatures.end(),
                        std::back_inserter(curSignatures),
                        [](std::shared_ptr<exec::FunctionSignature> signature)
                    -> exec::FunctionSignature * {
                            return signature.get();
                        });
                }
            });
        }
    } // namespace

    FunctionSignatureMap get_function_signatures() {
        FunctionSignatureMap result;
        populate_simple_function_signatures(result);
        populate_vector_function_signatures(result);
        return result;
    }

    std::vector<const exec::FunctionSignature *> get_function_signatures(
        const std::string &functionName) {
        // Some functions have both simple and vector implementations (for different
        // signatures). Collect all signatures.
        // Check simple functions first.
        auto signatures = exec::simple_functions().get_function_signatures(functionName);

        // Check vector functions.
        auto &vectorFunctions = exec::vectorFunctionFactories();
        vectorFunctions.withRLock([&](const auto &functions) {
            auto it = functions.find(functionName);
            if (it != functions.end()) {
                for (const auto &signature: it->second.signatures) {
                    signatures.push_back(signature.get());
                }
            }
        });

        return signatures;
    }

    FunctionSignatureMap getVectorFunctionSignatures() {
        FunctionSignatureMap result;
        populate_vector_function_signatures(result);
        return result;
    }

    void clearFunctionRegistry() {
        exec::mutable_simple_functions().clear_registry();
        exec::vectorFunctionFactories().withWLock(
            [](auto &functionMap) { functionMap.clear(); });
    }

    std::optional<bool> isDeterministic(const std::string &functionName) {
        const auto functions =
                exec::simple_functions().get_function_signatures_and_metadata(functionName);
        const auto metadata = exec::getVectorFunctionMetadata(functionName);
        if (functions.empty() && !metadata.has_value()) {
            return std::nullopt;
        }

        for (const auto &[metadata_2, _]: functions) {
            if (!metadata_2.deterministic) {
                return false;
            }
        }
        if (metadata.has_value() && !metadata.value().deterministic) {
            return false;
        }
        return true;
    }

    TypePtr resolve_function(
        const std::string &functionName,
        const std::vector<TypePtr> &argTypes) {
        // Check if this is a simple function.
        if (auto returnType = resolveSimpleFunction(functionName, argTypes)) {
            return returnType;
        }

        // Check if VectorFunctions has this function name + signature.
        return resolveVectorFunction(functionName, argTypes);
    }

    std::optional<std::pair<TypePtr, exec::VectorFunctionMetadata> >
    resolveFunctionWithMetadata(
        const std::string &functionName,
        const std::vector<TypePtr> &argTypes) {
        if (auto resolvedFunction =
                exec::simple_functions().resolve_function(functionName, argTypes)) {
            return std::pair<TypePtr, exec::VectorFunctionMetadata>{
                resolvedFunction->type(), resolvedFunction->metadata()
            };
        }

        return exec::resolveVectorFunctionWithMetadata(functionName, argTypes);
    }

    TypePtr resolveFunctionOrCallableSpecialForm(
        const std::string &functionName,
        const std::vector<TypePtr> &argTypes) {
        if (auto returnType = resolveCallableSpecialForm(functionName, argTypes)) {
            return returnType;
        }

        return resolve_function(functionName, argTypes);
    }

    TypePtr resolveCallableSpecialForm(
        const std::string &functionName,
        const std::vector<TypePtr> &argTypes) {
        return exec::resolveTypeForSpecialForm(functionName, argTypes);
    }

    TypePtr resolveSimpleFunction(
        const std::string &functionName,
        const std::vector<TypePtr> &argTypes) {
        if (auto resolvedFunction =
                exec::simple_functions().resolve_function(functionName, argTypes)) {
            return resolvedFunction->type();
        }

        return nullptr;
    }

    TypePtr resolveVectorFunction(
        const std::string &functionName,
        const std::vector<TypePtr> &argTypes) {
        return exec::resolveVectorFunction(functionName, argTypes);
    }

    std::optional<std::pair<TypePtr, exec::VectorFunctionMetadata> >
    resolveVectorFunctionWithMetadata(
        const std::string &functionName,
        const std::vector<TypePtr> &argTypes) {
        return exec::resolveVectorFunctionWithMetadata(functionName, argTypes);
    }

    void removeFunction(const std::string &functionName) {
        exec::mutable_simple_functions().removeFunction(functionName);
        exec::vectorFunctionFactories().withWLock(
            [&](auto &functionMap) { functionMap.erase(functionName); });
    }
} // namespace kumo::pollux
